<?php

namespace app\admin\model\report;

use app\admin\model\basic\Assets;
use app\admin\model\basic\Goods;
use app\admin\model\business\AssetsLog;
use app\admin\model\business\StashGoodsDetail;
use fast\Auth;
use think\Model;
use traits\model\SoftDelete;

class StashDetail extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'stash_detail';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return [
            '100' => __('Status 100'),
            '200' => __('Status 200'),
            //   '300' => __('Status 300'),
            '400' => __('Status 400'),
            '500' => __('Status 500'),
            "1300" => __('调拨单'),
            "1400" => __('其他入库单'),
            "1500" => __('其他出库单'),
        ];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    /**
     * Notes: 删除单据详情 恢复相关日志 库存信息
     * User: AerYYY
     * Date: 5/9/24 10:15 AM
     * @param $ids
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delLog($ids)
    {
        $info = $this->where('id', $ids)->find();
        if (empty($info)) {
            $this->error = '未找到有效的订单';
            return false;
        }

        switch ($info['status']) {
            case 100:  //销售单
                if (!$this->delXsd($info)) {
                    return false;
                }
                break;
            case 200: //销售退货单
                if (!$this->delXsthd($info)) {
                    return false;
                }
                break;
            case 400: //进货单
                if (!$this->delJhd($info)) {
                    return false;
                }
                break;
            case 500://退货单
                if (!$this->delThd($info)) {
                    return false;
                }
                break;
            case 1300://调拨单
                if (!$this->delDbd($info['order_no'])) {
                    return false;
                }
                break;
            case 1400://其他入库单
                if (!$this->delQtrkd($info)) {
                    return false;
                }
                break;
            case 1500://其他出库单
                if (!$this->delQtckd($info)) {
                    return false;
                }
                break;
            default:
                $this->error = '异常类型';
                return false;
        }

        return true;
    }


    /**
     * Notes: 调拨单删除
     * User: AerYYY
     * Date: 5/9/24 7:33 PM
     * @param $order_no
     * @return true
     */
    public function delDbd($order_no)
    {
        $stashGoodsDetails = new StashGoodsDetail();
        $stashGoodsDetails->where('order_no', $order_no)->delete();

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;
    }

    /**
     * Notes: 删除销售单
     * User: AerYYY
     * Date: 5/9/24 8:01 PM
     * @param $order
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delXsd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty + $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty += $item['qty'];

                $stashGoodsDetails->save([
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 1,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_XSD,
                ]);
            }
        }

        $assetsModel = new Assets();
        $assets = $assetsModel->where('id', $order['assets_id'])->find();
        if (empty($assets)) {
            $this->error = '错误的账户';
            return false;
        }

        $assetsLogModel = new AssetsLog();
        $assetsLogPrice = $assetsLogModel->where('order_no', $order['order_no'])->where('be',1)->sum('price')
        -$assetsLogModel->where('order_no', $order['order_no'])->where('be',2)->sum('price');

        $assets->balance = bcsub($assets->balance, $assetsLogPrice, 2);
        $assets->save();

        $assetsLogModel = new AssetsLog();
        $data = [
            'staff_id' => $order['staff_id'] ?? 0,
            'assets_id' => $order['assets_id'],
            'status' => Finance::STATUS_SYSTEM_DEL_XSD,
            'order_no' => $order['order_no'],
            'date' => $order['date'],
            'be' => 2,
            'price' => $assetsLogPrice,
        ];
        $assetsLogModel->createLog($data);

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;

    }

    /**
     * Notes:  销售退货单删除
     * User: AerYYY
     * Date: 5/9/24 8:14 PM
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delXsthd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty - $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty -= $item['qty'];

                $stashGoodsDetails->save([// 库存详细日志
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 2,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_XSTHD,
                ]);
            }
        }

        $assetsModel = new Assets();
        $assets = $assetsModel->where('id', $order['assets_id'])->find();
        if (empty($assets)) {
            $this->error = '错误的账户';
            return false;
        }
        $assetsLogModel = new AssetsLog();
        $assetsLogPrice = $assetsLogModel->where('order_no', $order['order_no'])->where('be',2)->sum('price')
            -$assetsLogModel->where('order_no', $order['order_no'])->where('be',1)->sum('price');

        $assets->balance = bcadd($assets->balance, $assetsLogPrice, 2);
        $assets->save();

        $assetsLogModel = new AssetsLog();
        $data = [
            'staff_id' => $order['staff_id'] ?? 0,
            'assets_id' => $order['assets_id'],
            'status' => Finance::STATUS_SYSTEM_DEL_XSTHD,
            'order_no' => $order['order_no'],
            'date' => $order['date'],
            'be' => 1,
            'price' => $assetsLogPrice,
        ];
        $assetsLogModel->createLog($data);

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;

    }

    /**
     * Notes: 删除进货单
     * User: AerYYY
     * Date: 5/9/24 8:28 PM
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delJhd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty - $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty -= $item['qty'];

                $stashGoodsDetails->save([
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 2,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_JHD,
                ]);
            }
        }

        $assetsModel = new Assets();
        $assets = $assetsModel->where('id', $order['assets_id'])->find();
        if (empty($assets)) {
            $this->error = '错误的账户';
            return false;
        }
        $assetsLogModel = new AssetsLog();
        $assetsLogPrice = $assetsLogModel->where('order_no', $order['order_no'])->where('be',2)->sum('price')
            -$assetsLogModel->where('order_no', $order['order_no'])->where('be',1)->sum('price');

        $assets->balance = bcadd($assets->balance, $assetsLogPrice, 2);
        $assets->save();

        $assetsLogModel = new AssetsLog();
        $data = [
            'staff_id' => $order['staff_id'] ?? 0,
            'assets_id' => $order['assets_id'],
            'status' => Finance::STATUS_SYSTEM_DEL_JHD,
            'order_no' => $order['order_no'],
            'date' => $order['date'],
            'be' => 1,
            'price' => $assetsLogPrice,
        ];
        $assetsLogModel->createLog($data);

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;

    }

    /**
     * Notes: 删除退货单
     * User: AerYYY
     * Date: 5/9/24 8:58 PM
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delThd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty + $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty += $item['qty'];

                $stashGoodsDetails->save([
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 1,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_THD,
                ]);
            }
        }

        $assetsModel = new Assets();
        $assets = $assetsModel->where('id', $order['assets_id'])->find();
        if (empty($assets)) {
            $this->error = '错误的账户';
            return false;
        }
        $assetsLogModel = new AssetsLog();
        $assetsLogPrice = $assetsLogModel->where('order_no', $order['order_no'])->where('be',1)->sum('price')
            - $assetsLogModel->where('order_no', $order['order_no'])->where('be',2)->sum('price');

        $assets->balance = bcsub($assets->balance, $assetsLogPrice, 2);
        $assets->save();

        $assetsLogModel = new AssetsLog();
        $data = [
            'staff_id' => $order['staff_id'] ?? 0,
            'assets_id' => $order['assets_id'],
            'status' => Finance::STATUS_SYSTEM_DEL_THD,
            'order_no' => $order['order_no'],
            'date' => $order['date'],
            'be' => 2,
            'price' => $assetsLogPrice,
        ];
        $assetsLogModel->createLog($data);

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;

    }

    /**
     * Notes: 删除其他入库单
     * User: AerYYY
     * Date: 5/9/24 9:02 PM
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delQtrkd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty - $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty -= $item['qty'];

                $stashGoodsDetails->save([
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 2,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_QTRKD,
                ]);
            }
        }

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;
    }

    public function delQtckd($order)
    {
        $order_no = $order['order_no'];
        $stashGoodsDetails = new StashGoodsDetail();
        $list = $stashGoodsDetails->where('order_no', $order_no)->select();

        if (count($list)) {
            foreach ($list as $item) {
                $goodsModel = new Goods();
                $goods = $goodsModel->where('id', $item['goods_id'])->find();
                if (empty($goods)) {
                    $this->error = '错误的商品数据';
                    return false;
                }
                $goods->qty = $goods->qty + $item['qty'];
                $goods->save();  // 修改商品库存

                $stashGoodsDetails = new StashGoodsDetail();
                $stash_surplus_qty = 0;
                $stash_last = $stashGoodsDetails->where(['goods_id' => $item['goods_id'], 'stash_id' => $item['stash_id']])->order('createtime desc')
                    ->find();
                if (!empty($stash_last)) {
                    $stash_surplus_qty = $stash_last['stash_surplus_qty'];
                }
                $stash_surplus_qty += $item['qty'];

                $stashGoodsDetails->save([
                    'order_no' => $item['order_no'],
                    'goods_id' => $item['goods_id'],
                    'be' => 1,
                    'qty' => $item['qty'],
                    'stash_id' => $item['stash_id'],
                    'surplus_qty' => $goods->qty,
                    'stash_surplus_qty' => $stash_surplus_qty,
                    'cost_price' => $item['cost_price'],
                    'cost_amount' => $item['cost_amount'],
                    'price' => $item['price'] ?? 0,
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'status' => Finance::STATUS_SYSTEM_DEL_QTCKD,
                ]);
            }
        }

        $financeModel = new Finance();
        $financeModel->where('order_no', $order_no)->delete();
        return true;
    }
}
